package _interview150;

/**
 * 238. 除自身以外数组的乘积
 */
public class No238 {
    /**
     * 1. 使用额外数组
     */
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;

        int[] pre = new int[n];
        pre[0] = 1;
        for (int i = 1; i < n; i++) {
            pre[i] = pre[i - 1] * nums[i - 1];
        }

        int[] suf = new int[n];
        suf[n - 1] = 1;
        for (int i = n - 2; i >= 0; i--) {
            suf[i] = suf[i + 1] * nums[i + 1];
        }

        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = pre[i] * suf[i];
        }
        return ans;
    }

    /**
     * 2. O(1) 的额外空间复杂度
     */
    public int[] productExceptSelf2(int[] nums) {
        int n = nums.length;

        int[] ans = new int[n];
        ans[0] = 1;
        for (int i = 1; i < n; i++) {
            ans[i] = ans[i - 1] * nums[i - 1];
        }

        int suf = 1;
        for (int i = n - 1; i >= 0; i--) {
            ans[i] = ans[i] * suf;
            suf *= nums[i];
        }

        return ans;
    }
}